<script>
// 引入 vue3 的响应式和 nextTick 方法
import { ref, nextTick, onMounted } from 'vue'
// 引入 vue-router 的路由方法
import { useRouter } from 'vue-router'
// 引入 pinia 的全局状态管理
import { useMenuStore } from '@/store/index'
// 引入 axios 用于请求后端接口
import axios from 'axios'
// 引入 Element Plus 的消息组件
import { ElMessage } from 'element-plus'
// 引入 Aside 侧边栏组件
import Aside from './Aside.vue'

export default {
    name: "Main",
    setup() {
        // 路由实例
        const router = useRouter()
        // pinia 全局菜单 store 实例
        const menuStore = useMenuStore()
        // 自动恢复动态菜单和路由
        onMounted(() => {
            const menuList = JSON.parse(sessionStorage.getItem('menuList') || '[]')
            if (menuList.length) {
                menuStore.setMenu(menuList)
            }
        })
        // 获取全局菜单数据
        const menu = menuStore.menu
        // 表单引用
        const formRef = ref(null)

        // 表格数据
        const tableData = ref([])
        // 分页相关参数
        const pageSize = ref(10)
        const pageNum = ref(1)
        const total = ref(0)
        // 查询参数
        const name = ref('')
        const sex = ref('')
        // 控制弹窗显示
        const centerDialogVisible = ref(false)

        // 性别选项
        const sexs = ref([
            { value: '1', label: '男' },
            { value: '0', label: '女' }
        ])

        // 表单数据
        const form = ref({
            id: '',
            no: '',
            name: '',
            password: '',
            age: '',
            phone: '',
            sex: '0',
            roleId: '1'
        })

        // 年龄校验
        const checkAge = (rule, value, callback) => {
            if (value > 150) {
                callback(new Error('年龄输入过大'))
            } else {
                callback()
            }
        }

        // 账号重复校验
        const checkDuplicate = (rule, value, callback) => {
            if (form.value.id) {
                return callback()
            }
            axios.get(import.meta.env.VITE_HTTP_URL + "/user/findByNo?no=" + form.value.no)
                .then(res => res.data)
                .then(res => {
                    if (res.code != 200) {
                        callback()
                    } else {
                        callback(new Error('账号已经存在'))
                    }
                })
        }

        // 表单校验规则
        const rules = ref({
            no: [
                { required: true, message: '请输入账号', trigger: 'blur' },
                { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
                { validator: checkDuplicate, trigger: 'blur' }
            ],
            name: [
                { required: true, message: '请输入名字', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
            ],
            age: [
                { required: true, message: '请输入年龄', trigger: 'blur' },
                { min: 1, max: 3, message: '长度在 1 到 3 个位', trigger: 'blur' },
                { pattern: /^([1-9][0-9]*){1,3}$/, message: '年龄必须为正整数字', trigger: "blur" },
                { validator: checkAge, trigger: 'blur' }
            ],
            phone: [
                { required: true, message: "手机号不能为空", trigger: "blur" },
                { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
            ]
        })
        // 重置表单
        const resetForm = () => {
            formRef.value?.resetFields()
        }

        // 删除用户
        const del = (id) => {
            console.log(id)
            axios.get(import.meta.env.VITE_HTTP_URL + '/user/del?id=' + id)
                .then(res => res.data)
                .then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        ElMessage.success('操作成功！')
                        loadPost()
                    } else {
                        ElMessage.error('操作失败！')
                    }
                })
        }

        // 编辑用户，弹窗回填数据
        const mod = (row) => {
            console.log(row)
            centerDialogVisible.value = true
            nextTick(() => {
                form.value.id = row.id
                form.value.no = row.no
                form.value.name = row.name
                form.value.password = ''
                form.value.age = row.age + ''
                form.value.sex = row.sex + ''
                form.value.phone = row.phone
                form.value.roleId = row.roleId
            })
        }

        // 新增用户，弹窗并重置表单
        const add = () => {
            centerDialogVisible.value = true
            nextTick(() => {
                resetForm()
            })
        }

        // 保存用户（新增）
        const doSave = () => {
            axios.post(import.meta.env.VITE_HTTP_URL + '/user/save', form.value)
                .then(res => res.data)
                .then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        ElMessage.success('操作成功！')
                        centerDialogVisible.value = false
                        loadPost()
                        resetForm()
                    } else {
                        ElMessage.error('操作失败！')
                    }
                })
        }

        // 保存用户（修改）
        const doMod = () => {
            axios.post(import.meta.env.VITE_HTTP_URL + '/user/update', form.value)
                .then(res => res.data)
                .then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        ElMessage.success('操作成功！')
                        centerDialogVisible.value = false
                        loadPost()
                        resetForm()
                    } else {
                        ElMessage.error('操作失败！')
                    }
                })
        }

        // 表单保存（区分新增/修改）
        const save = async () => {
            try {
                await formRef.value.validate()
                if (form.value.id) {
                    await doMod()
                } else {
                    await doSave()
                }
            } catch (error) {
                console.log('表单验证失败', error)
                return false
            }
        }

        // 分页大小变化
        const handleSizeChange = (val) => {
            console.log(`每页 ${val} 条`)
            pageNum.value = 1
            pageSize.value = val
            loadPost()
        }

        // 当前页变化
        const handleCurrentChange = (val) => {
            console.log(`当前页: ${val}`)
            pageNum.value = val
            loadPost()
        }

        // 获取全部用户（未分页）
        const loadGet = () => {
            axios.get(import.meta.env.VITE_HTTP_URL + '/user/list')
                .then(res => res.data)
                .then(res => {
                    console.log(res)
                })
        }

        // 重置查询参数
        const resetParam = () => {
            name.value = ''
            sex.value = ''
        }

        // 分页查询用户列表
        const loadPost = () => {
            axios.post(import.meta.env.VITE_HTTP_URL + '/user/listPageC1', {
                pageSize: pageSize.value,
                pageNum: pageNum.value,
                param: {
                    name: name.value,
                    sex: sex.value
                }
            }).then(res => res.data)
                .then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        tableData.value = res.data
                        total.value = res.total
                    } else {
                        alert('获取数据失败')
                    }
                })
        }

        // 组件挂载时加载数据
        loadPost()


        return {
            formRef,
            tableData,
            pageSize,
            pageNum,
            total,
            name,
            sex,
            sexs,
            centerDialogVisible,
            form,
            rules,
            resetForm,
            del,
            mod,
            add,
            save,
            handleSizeChange,
            handleCurrentChange,
            resetParam,
            loadPost,
            // 暴露全局菜单状态
            menu,
            Aside
        }
    }
}
</script>



<template>
    <!-- 用户管理主页面 -->
    <div style="display: flex;">
        <!-- 左侧菜单栏 -->
        <Aside :menu="menu" />
        <!-- 右侧内容区 -->
        <div style="flex: 1; padding-left: 20px;">
            <!-- 查询与操作区 -->
            <div style="margin-bottom: 5px;">
                <!-- 姓名查询输入框 -->
                <el-input v-model="name" placeholder="请输入名字" suffix-icon="el-icon-search" style="width: 200px;"
                    @keyup.enter="loadPost"></el-input>
                <!-- 性别选择框 -->
                <el-select v-model="sex" filterable placeholder="请选择性别" style="margin-left: 5px;">
                    <el-option v-for="item in sexs" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
                <!-- 查询按钮 -->
                <el-button type="primary" style="margin-left: 5px;" @click="loadPost">查询</el-button>
                <!-- 重置按钮 -->
                <el-button type="success" @click="resetParam">重置</el-button>

                <!-- 新增用户按钮 -->
                <el-button type="primary" style="margin-left: 5px;" @click="add">新增</el-button>
            </div>
            <!-- 用户表格 -->
            <el-table :data="tableData" :header-cell-style="{ background: '#f2f5fc', color: '#555555' }" border>
                <el-table-column prop="id" label="ID" width="60">
                </el-table-column>
                <el-table-column prop="no" label="账号" width="180">
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="age" label="年龄" width="80">
                </el-table-column>
                <el-table-column prop="sex" label="性别" width="80">
                    <template #default="scope">
                        <!-- 性别标签 -->
                        <el-tag :type="scope.row.sex === 1 ? 'primary' : 'success'" disable-transitions>{{ scope.row.sex
                            ===
                            1 ? '男' : '女' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="roleId" label="角色" width="120">
                    <template #default="scope">
                        <!-- 角色标签 -->
                        <el-tag
                            :type="scope.row.roleId === 0 ? 'danger' : (scope.row.roleId === 1 ? 'primary' : 'success')"
                            disable-transitions>{{ scope.row.roleId === 0 ? '超级管理员' :
                                (scope.row.roleId === 1 ? '管理员' : '用户') }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="电话" width="180">
                </el-table-column>
                <el-table-column prop="operate" label="操作">
                    <template #default="scope">
                        <!-- 编辑按钮 -->
                        <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                        <!-- 删除按钮，带确认弹窗 -->
                        <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)" style="margin-left: 5px;">
                            <el-button slot="reference" size="small" type="danger">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                :page-sizes="[5, 10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>

            <!-- 新增/编辑弹窗表单 -->
            <el-dialog title="提示" v-model="centerDialogVisible" width="30%" center>

                <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
                    <el-form-item label="账号" prop="no">
                        <el-col :span="20">
                            <el-input v-model="form.no"></el-input>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="名字" prop="name">
                        <el-col :span="20">
                            <el-input v-model="form.name"></el-input>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-col :span="20">
                            <el-input v-model="form.password"></el-input>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="年龄" prop="age">
                        <el-col :span="20">
                            <el-input v-model="form.age"></el-input>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="form.sex">
                            <el-radio label="1">男</el-radio>
                            <el-radio label="0">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="电话" prop="phone">
                        <el-col :span="20">
                            <el-input v-model="form.phone"></el-input>
                        </el-col>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>



<style scoped></style>
